//jqGrid的配置信息
$.jgrid.defaults.width = 1000;
$.jgrid.defaults.responsive = true;
$.jgrid.defaults.styleUI = 'Bootstrap';

var baseURL = "../";
var baseURL3 = "../../../";

//工具集合Tools
window.T = {};

// 获取请求参数
// 使用示例
// location.href = http://localhost:8080/index.html?id=123
// T.p('id') --> 123;
var url = function(name) {
	var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if(r!=null)return  unescape(r[2]); return null;
};
T.p = url;

//全局配置
$.ajaxSetup({
	dataType: "json",
	cache: false
});

//重写alert 
window.alert = function(msg, callback){//parent.
	layer.alert(msg, function(index){
		layer.close(index);
		if(typeof(callback) === "function"){
			callback("ok");
		}
	});
}

//重写confirm式样框
window.confirm = function(msg, callback){
	layer.confirm(msg, {btn: ['确定','取消']},
	function(){//确定事件
		if(typeof(callback) === "function"){
			callback("ok");
		}
	});
}

//选择一条记录
function getSelectedRow() {
    var grid = $("#jqGrid");
    var rowKey = grid.getGridParam("selrow");
    if(!rowKey){
    	alert("请选择一条记录");
    	return ;
    }
    
    var selectedIDs = grid.getGridParam("selarrrow");
    if(selectedIDs.length > 1){
    	alert("只能选择一条记录");
    	return ;
    }
    
    return selectedIDs[0];
}

function getSelectedRownoalert() {
    var grid = $("#jqGrid");
    var rowKey = grid.getGridParam("selrow");
    if(!rowKey){
    	//alert("请选择一条记录");
    	return ;
    }
    
    var selectedIDs = grid.getGridParam("selarrrow");
    if(selectedIDs.length > 1){
    	alert("只能选择一条记录");
    	return ;
    }
    
    return selectedIDs[0];
}

//选择多条记录
function getSelectedRows() {
    var grid = $("#jqGrid");
    var rowKey = grid.getGridParam("selrow");
    if(!rowKey){
    	alert("请选择一条记录");
    	return ;
    }
    
    return grid.getGridParam("selarrrow");
}

//判断是否为空
function isBlank(value) {
    return !value || !/\S/.test(value)
}

//内嵌select2
Vue.directive('select2', {
    inserted: function (el, binding, vnode) {
        var options = binding.value || {};

        $(el).select2(options).on("select2:select", function(e){
            // v-model looks for
            //  - an event named "change"
            //  - a value with property path "$event.target.value"
            el.dispatchEvent(new Event('change', { target: e.target })); //说好的双向绑定，竟然不安套路
//            console.log("fire change in insert");
        });
    },
    update: function (el, binding, vnode) {
        for (var i = 0; i < vnode.data.directives.length; i++) {
            if (vnode.data.directives[i].name == "model") {
                $(el).val(vnode.data.directives[i].value);
//                console.log("new value in update:"+vnode.data.directives[i].value);
            }
        }
        $(el).trigger("change");
//        console.log("fire change in update");
    }
});


//add by xucg
//文件上传
function fileup(type){
	var baseurl = baseURL;
	if(type==3){// 三层路径页面
		baseurl = baseURL3;
	}
	
	layer.open({
		type : 2,
		offset : '20px',
		skin : 'layui-layer-molv',
		title : "选择附件",
		area : [ '700px', '400px'],
		shade : 0.2,
		shadeClose : false,
		content : baseurl+"modules/sys/fileup.html",
		btn : [ '确定', '取消' ],
		yes: function(index,layero){
			var body = layer.getChildFrame('body', index);
//		    var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
		    var mark = body.find('#mark').val();
		    var gid = body.find('#getidall').html();
		    
		   console.log("获得的mark "+mark+"----- id "+gid);
		   if(gid==""||gid==null||gid=="undefined"){
			   alert("上传失败，请重新上传");
			   return false;
		   }
		   
		   var befGid =  $('#getallfileid').html();// 这次上传之前的值，用于取消上传后回写
		   $('#getallfileid').append(gid); 
		   
		   $.ajax({
				type: "get",
			    url: baseurl + "ins/sysfiletable/updatemark",
			    async: false,
		        contentType: "application/json",
			    data:{"mark":mark,"ids":gid},
			    success: function(r){
			    	console.log(r);
			    	if(r == "fail"){
			    		alert("上传失败");
			    	}
				}
			});
		   if (typeof(fileUploadCallback) == "function") {// 回调函数
				var callBack = fileUploadCallback(mark);
				if(!callBack && callBack!=undefined){
					$('#getallfileid').html(befGid);
					return;
				} 
		   }
		   
		   layer.close(index);
		 }
	});
}

//点击查看附件触发
function ckfile(getid,type,nodel){
	var baseurl = baseURL;
	if(type==3){// 三层路径页面
		baseurl = baseURL3;
	}
	
	layer.open({
		type : 2,
		offset : '20px',
		skin : 'layui-layer-molv',
		title : "选择附件",
		area : [ '950px', '450px' ],//590px
		shade :  [0.1, '#fff'],
		shadeClose : false,
		content : baseurl+"modules/sys/sysfiletable.html?getallid="+getid+"&&nodel="+nodel,
		btn : [ '关闭' ],
        success: function(layero, index) {
            layerResize(index);
        }
	});

}
/*layerindex  layer宽高     层级*/
function resizeLayer(layerIndex,layerInitWidth,layerInitHeight,hierarchy) {
//		var docWidth = $("#myIframe" , parent.document).width()-10;
//		var docHeight =  $("#myIframe" , parent.document).height();

    if(hierarchy==1){
        var pageWidth = parent.window.innerWidth,
            pageHeight = parent.window.innerHeight;

        if (typeof pageWidth != "number"){
            //标准模式
            if (document.compatMode == "CSS1Compat"){
                pageWidth = parent.document.documentElement.clientWidth;
                pageHeight = parent.document.documentElement.clientHeight;
                //怪异模式
            } else {
                pageWidth = parent.document.body.clientWidth;
                pageHeight = parent.document.body.clientHeight;
            }
        }

        var docWidth = pageWidth-10;
        var docHeight =  pageHeight-50;
        console.log("doc:",docWidth,docHeight);

        if((layerInitWidth > docWidth || layerInitHeight > docHeight) && docWidth>0 && docHeight>0){
            var minWidth = layerInitWidth > docWidth ? docWidth : layerInitWidth;
            var minHeight = layerInitHeight > docHeight ? docHeight : layerInitHeight;
            console.log("lay:",layerInitWidth,layerInitHeight);
            console.log("min:",minWidth,minHeight);

            parent.layer.style(layerIndex, {
                top:10,
                width: minWidth,
                height:minHeight
            });
        }
    }else if(hierarchy==2){
        var pageWidth = parent.parent.window.innerWidth,
            pageHeight = parent.parent.window.innerHeight;

        if (typeof pageWidth != "number"){
            //标准模式
            if (document.compatMode == "CSS1Compat"){
                pageWidth = parent.parent.document.documentElement.clientWidth;
                pageHeight = parent.parent.document.documentElement.clientHeight;
                //怪异模式
            } else {
                pageWidth = parent.parent.document.body.clientWidth;
                pageHeight = parent.parent.document.body.clientHeight;
            }
        }

        var docWidth = pageWidth-10;
        var docHeight =  pageHeight-50;
        console.log("doc:",docWidth,docHeight);

        if((layerInitWidth > docWidth || layerInitHeight > docHeight) && docWidth>0 && docHeight>0){
            var minWidth = layerInitWidth > docWidth ? docWidth : layerInitWidth;
            var minHeight = layerInitHeight > docHeight ? docHeight : layerInitHeight;
            console.log("lay:",layerInitWidth,layerInitHeight);
            console.log("min:",minWidth,minHeight);

            parent.parent.layer.style(layerIndex, {
                top:10,
                width: minWidth,
                height:minHeight
            });
        }
    }else if(hierarchy==3){
        var pageWidth = parent.parent.parent.window.innerWidth,
            pageHeight = parent.parent.parent.window.innerHeight;

        if (typeof pageWidth != "number"){
            //标准模式
            if (document.compatMode == "CSS1Compat"){
                pageWidth = parent.parent.parent.document.documentElement.clientWidth;
                pageHeight = parent.parent.parent.document.documentElement.clientHeight;
                //怪异模式
            } else {
                pageWidth = parent.parent.parent.document.body.clientWidth;
                pageHeight = parent.parent.parent.document.body.clientHeight;
            }
        }

        var docWidth = pageWidth-10;
        var docHeight =  pageHeight-50;
        console.log("doc:",docWidth,docHeight);

        if((layerInitWidth > docWidth || layerInitHeight > docHeight) && docWidth>0 && docHeight>0){
            var minWidth = layerInitWidth > docWidth ? docWidth : layerInitWidth;
            var minHeight = layerInitHeight > docHeight ? docHeight : layerInitHeight;
            console.log("lay:",layerInitWidth,layerInitHeight);
            console.log("min:",minWidth,minHeight);

            parent.parent.parent.layer.style(layerIndex, {
                top:10,
                width: minWidth,
                height:minHeight
            });
        }
    }else{
        var pageWidth = window.innerWidth,
            pageHeight = window.innerHeight;

        if (typeof pageWidth != "number"){
            //标准模式
            if (document.compatMode == "CSS1Compat"){
                pageWidth = document.documentElement.clientWidth;
                pageHeight = document.documentElement.clientHeight;
                //怪异模式
            } else {
                pageWidth = document.body.clientWidth;
                pageHeight = document.body.clientHeight;
            }
        }

        var docWidth = pageWidth-10;
        var docHeight =  pageHeight-50;
        console.log("doc:",docWidth,docHeight);

        if((layerInitWidth > docWidth || layerInitHeight > docHeight) && docWidth>0 && docHeight>0){
            var minWidth = layerInitWidth > docWidth ? docWidth : layerInitWidth;
            var minHeight = layerInitHeight > docHeight ? docHeight : layerInitHeight;
            console.log("lay:",layerInitWidth,layerInitHeight);
            console.log("min:",minWidth,minHeight);

            layer.style(layerIndex, {
                top:10,
                width: minWidth,
                height:minHeight
            });
        }
    }

    $(window).resize()

}


//如果宽高超出窗口重新设置layer宽高
function layerResize(layerIndex,hierarchy) {
    var layerInitWidth, layerInitHeight;

    if(hierarchy==1){
        layerInitWidth  = parent.$("#layui-layer"+layerIndex).width();
        layerInitHeight = parent.$("#layui-layer"+layerIndex).height();
    }else if(hierarchy==2){
        layerInitWidth  = parent.parent.$("#layui-layer"+layerIndex).width();
        layerInitHeight = parent.parent.$("#layui-layer"+layerIndex).height();
    }else if(hierarchy==3){
        layerInitWidth  = parent.parent.parent.$("#layui-layer"+layerIndex).width();
        layerInitHeight = parent.parent.parent.$("#layui-layer"+layerIndex).height();
    }else{
        layerInitWidth  = $("#layui-layer"+layerIndex).width();
        layerInitHeight = $("#layui-layer"+layerIndex).height();
    }

    resizeLayer(layerIndex,layerInitWidth,layerInitHeight,hierarchy);
}


function dictmanage(type,id){
    layer.open({
        type : 2,
        offset : '10px',
        skin : 'layui-layer-molv',
        title : "字典管理",
        area : [ '900px', '500px' ],
        shade : 0.2,
        shadeClose : false,
        content : baseURL+"modules/sys/dictmanage.html?type="+type+"&&parentId=0",
        btn : [ '确定', '取消' ],
        success: function(layero, index) {
            //获取当前弹出窗口的索引及初始大小
            var layerIndex = index;
            var layerInitWidth  = $("#layui-layer"+layerIndex).width();
            var layerInitHeight = $("#layui-layer"+layerIndex).height();
            resizeLayer(layerIndex,layerInitWidth,layerInitHeight);
        },
        yes: function(index,layero){
            layer.close(index);
        },
        end:function(layero, index){
        }

    });

}


//select2下拉加载模式反选
function se2CheckValue(domid,value,text){
    if(!isBlank(value)){
        $("#"+domid).append(new Option(text, value, false, true));
        $("#"+domid).trigger('change');
    }else{
        $("#"+ domid +" option").remove()
    }
}

//select2下拉加载模式清空选项
function se2RemoveCheck(domid){
    $("#"+ domid +" option").remove()
}

//---------------------------------------------------
//日期格式化
//dateFmt("yyyy-MM-dd hh:mm:ss",new Date())
//---------------------------------------------------
function dateFmt(fmt,date)
{ //author: meizz
    var o = {
        "M+" : date.getMonth()+1,                 //月份
        "d+" : date.getDate(),                    //日
        "h+" : date.getHours(),                   //小时
        "m+" : date.getMinutes(),                 //分
        "s+" : date.getSeconds(),                 //秒
        "q+" : Math.floor((date.getMonth()+3)/3), //季度
        "S"  : date.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt))
        fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    return fmt;
}


var numRegex = /^\d+$/;// 正整数
var intRegex = /^-?\d+$/;// 整数
